var Banner = require("../models/banner");

// 轮播管理
exports.getBanner = function(callback){
	Banner.find({
		isShow: true
	}).sort({sort:"asc"}).exec(function (err, banner) {
		if (err) {
			return callback(err)
		} else {
			return callback(null, banner)
		}
	});
}

//后台
//轮播列表
exports.bannerList = function (req, res) {
	var pageSize = 20; //每页显示条数
	var page = req.params.num - 1 || 0;
	Banner.find().count().exec(function (err, sum) {
		Banner.find().limit(pageSize).skip(pageSize*page).sort({sort:"asc"}).exec(function (err,banner) {
				res.render('admin/bannerList', {
					title: '轮播列表',
					banner: banner,
					pagesize: sum
				})
		});
	});
}
//添加轮播
exports.bannerAdd = function (req, res) {
	res.render("admin/bannerAdd", {
		title: "添加轮播"
	});
}

//更新轮播
exports.bannerUpdate = function (req, res) {
	var id = req.params.id;
	Banner.findOne({"_id":id},function (err, banner) {
		if (err) {
			console.log(err)
		}else {
			res.render("admin/bannerUpdate", {
				title: "编辑轮播",
				banner:banner
			});
		}

	});
}

//保存、编辑
exports.bannerSave = function (req, res) {
	var _banner = req.body;
	var id = _banner._id;
	if (id) {
		Banner.update({
			_id: id
		}, _banner, function (err, _banner) {
			if(err){
				console.log(err)
			}
			res.send({"success":true,bannerList:_banner,"msg":"更新成功"})
		});
	} else {
		delete _banner._id
		Banner.create(_banner, function (err, _banner) {
			if(err){
				console.log(err)
			}
			res.send({"success":true,bannerList:_banner,"msg":"提交成功"})
		});
	}
}

exports.bannerDelete = function (req, res) {
	var id = req.params.id;
	Banner.remove({
		_id: id
	}, function (err) {
		res.redirect("/admin/bannerList");
	})
}